package cn.lvji.sus.maps;

import cn.lvji.sus.LongToShortAlgorithm;
import cn.lvji.sus.Maps;
import cn.lvji.sus.db.JDBCUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 使用ConcurrentHashMap简单实现
 *
 * @author zhouzx
 */
public class SampleUrlMaps implements Maps {
    private Map<String, String> caches = new ConcurrentHashMap<>();

    public SampleUrlMaps() {
        addUrl("http://sports.qq.com/nba/", LongToShortAlgorithm.shortUrl("http://sports.qq.com/nba/"));
        addUrl("https://github.com/spring-projects/spring-framework", LongToShortAlgorithm.shortUrl("https://github.com/spring-projects/spring-framework"));
    }

    @Override
    public String maps(String url) {
        String cached = caches.get(url);
        if (cached == null) {
            return JDBCUtils.getLongUrl(url);
        }
        return cached;
    }

    @Override
    public void addUrl(String longUrl, String shortUrl) {
        caches.put(shortUrl, longUrl);
    }
}
